<script setup lang='ts'>

import { addTimePeriod, deleteTimePeriod, modifyTimePeriod, timePeriodList } from '@/api/interfaceApi/https';
import { ref } from 'vue';
import { dayjs, ElMessage, ElMessageBox } from 'element-plus';
import { Period } from '@/api/interfaceApi/params';

let timeList = ref([]);
// 渲染列表
function renderList(){
    timePeriodList().then((res:any)=>{
        if (res.code === 200){
            timeList.value =  res.rows.map((item:any)=>{
                return {id:item.id, date:item.startTime +'-'+item.endTime};
            });
        }
    });
}
renderList();
const addDialogVisible = ref(false);
const updateDialogVisible =ref(false);
const addValue = ref<[Date, Date]>([
    new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate(), 8, 40),
    new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate(), 9, 40),
]);
const updateValue = ref<[Date, Date]>([
    new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate(), 8, 40),
    new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate(), 9, 40),
]);
let arr = ref<string[]>([]);
// 删除时间段
const open = (index:number) => {
    arr.value.push(timeList.value[index].id);
    ElMessageBox.confirm(
        '此操作将永久删除该时间段, 是否继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            ElMessage({
                type: 'success',
                message: "删除成功",
            });
            deleteTimePeriod(arr.value).then((ref:any)=>{
                if (ref.code === 200) {
                    renderList();
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            });
        });
};
// 添加时间段
function addTime(){
    timeIsReasonable(addValue.value,1);
    addDialogVisible.value = false;
}
function encapsulatedAdd(timePeriod:Period){
    addTimePeriod(timePeriod).then((res:any)=>{
        console.log(res);
        if (res.code===200){
            ElMessage({
                type: 'success',
                message: "添加成功",
            });
            renderList();
        }
    });
}
// 时间段的逻辑判断
function timeIsReasonable(time:any,method:number){
    const startStamp  = new Date(new Date().getFullYear()+'-'+ (new Date().getMonth()+1)+'-' +new Date().getDate()+' 8:00').getTime();
    const endStamp = new Date(new Date().getFullYear()+'-'+ (new Date().getMonth()+1)+'-' +new Date().getDate()+' 18:00').getTime();
    const startValue  = new Date(new Date().getFullYear()+'-'+ (new Date().getMonth()+1)+'-' +new Date().getDate()+' '+dayjs(time[0]).format("HH:mm")).getTime();
    const endValue = new Date(new Date().getFullYear()+'-'+ (new Date().getMonth()+1)+'-' +new Date().getDate()+' '+dayjs(time[1]).format("HH:mm")).getTime();
    if (startValue >= startStamp &&   endValue<= endStamp){
        if ((endValue-startValue) >= (30 * 60 * 1000)){
            if (timeList.value.some((item)=>{
                return item.date === dayjs(time[0]).format("HH:mm")+'-'+dayjs(time[1]).format("HH:mm");
            })){
                ElMessage({
                    type: 'warning',
                    message: "此时间段已存在，请重新操作",
                });
            }else {
                const timePeriod = ref<Period>({
                    startTime:dayjs(addValue.value[0]).format("HH:mm"),
                    endTime:dayjs(addValue.value[1]).format("HH:mm")
                });
                method?encapsulatedAdd(timePeriod.value):encapsulatedUpdate();
            }
        }else {
            ElMessage({
                type: 'warning',
                message: "咨询时间需要超过30分钟",
            });
        }
    }else {
        ElMessage({
            type: 'warning',
            message: "开始时间不能小于8点，结束时间不能超过18点",
        });
    }
}
//
let timeId = ref<string>('');
// 打开编辑模态框
function updateDialog(index:number){
    const startStr = timeList.value[index].date.split('-')[0];
    const endStr = timeList.value[index].date.split('-')[1];
    timeId.value = timeList.value[index].id;
    updateValue.value = [
        new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate(), Number(startStr.split(':')[0]), Number(startStr.split(':')[1])),
        new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate(), Number(endStr.split(':')[0]), Number(endStr.split(':')[1])),
    ];
    updateDialogVisible.value = true;
}
// 修改时间段
function updateTime(){
    timeIsReasonable(updateValue.value,0);
    updateDialogVisible.value = false;
}
function encapsulatedUpdate(){
    const time = ref<Period>({
        id:timeId.value,
        startTime:dayjs(updateValue.value[0]).format("HH:mm"),
        endTime:dayjs(updateValue.value[1]).format("HH:mm")
    });
    modifyTimePeriod(time.value).then((res:any)=>{
        if (res.code===200){
            ElMessage({
                type: 'success',
                message: "修改成功",
            });
            renderList();
        }
    });
}
</script>

<template>
    <div class='time-setting-container'>
        <div class='time-setting-container-header'>
            <el-button type="primary"  @click="addDialogVisible = true">添加</el-button>
        </div>
        <el-table :data='timeList' border style="width: 100%;">
            <el-table-column prop="date" label="日期" align='center' />
            <el-table-column prop="name" label="操作" align='center' >
                <template #default='scope'>
                    <el-button link type="primary" size="small" @click="updateDialog(scope.$index)">
                        编辑
                    </el-button>
                    <el-button link type="primary" size="small" @click="open(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog class='timePeriodAdd' v-model="addDialogVisible" :show-close="true" width="50%" title='添加时间段'>
            <template #header>
                <span>添加时间段</span>
            </template>
            <span class='timePeriodText'>选择时间段</span>
            <el-time-picker
                v-model="addValue"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
            />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" plain @click="addTime">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog class='timePeriodAdd' v-model="updateDialogVisible" :show-close="true" width="50%" title='添加时间段'>
            <template #header="{ }">
                <span>编辑时间段</span>
            </template>
            <span class='timePeriodText'>编辑时间段</span>
            <el-time-picker
                v-model="updateValue"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
            />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="updateDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateTime">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped lang='scss'>
    .time-setting-container {
        margin: 40px 20px;
        .time-setting-container-header {
            margin-bottom: 20px;
        }
        .timePeriodAdd {

            .timePeriodText {
                font-weight: 700;
                margin-right: 20px;
            }
            .dialog-footer {
                text-align: center;
            }
        }
    }
    ::v-deep(.el-dialog__header){
        background-color: #1892ff;
        margin-right: 0;
        color: white;
    }
    ::v-deep(.el-dialog__header .el-dialog__close) {
        color: #fff;
    }
</style>
